package com.yld.car.market;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import com.yld.car.common.CompressImageUtils;
import com.yld.car.common.ConstantUtils;
import com.yld.car.common.ImageUtils;
import com.yld.car.common.NetworkProgressUtils;
import com.yld.car.common.UploadImageTask;
import com.yld.car.domain.DealerBaseInfo;
import com.yld.car.domain.UserInfo;

import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MyBaseUpdateActivity extends BaseActivity implements
		OnItemClickListener {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.base_list_items_circle_list);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);

		showBackButton();
		Button localButton = (Button) findViewById(R.id.rightButton);
		localButton.setVisibility(View.VISIBLE);
		localButton.setText("完成");
		localButton.setOnClickListener(completeOnClickListener);
		((TextView) findViewById(R.id.title)).setText("编辑资料");
		list1 = (ListView) findViewById(R.id.itemList);
		list1.setOnItemClickListener(this);
		d = mApp.getD();
		// 获取默认的经销商个人信息
		companyAddress = d.getAddress();
		companyIntro = d.getIntro();
		companyName = d.getCompname();
		companyCity = d.getProvincecity();
		companyPort = d.getPort();
		companyPrincipal = d.getComppeople();
		contactWay = d.getTelephone();
		companyImg = d.getUserimg();
		// if (companyImg != null) {
		// companyImg = companyImg.substring(companyImg.lastIndexOf("/") + 1,
		// companyImg.length());
		// }
		System.out.println(companyImg);
		b = mApp.getB();
		UpdateBaseInfoAdapter adapter = new UpdateBaseInfoAdapter(this);
		list1.setAdapter(adapter);
	}

	private ListView list1;
	private DealerBaseInfo d;
	private Bitmap b;
	View.OnClickListener completeOnClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {

			new UpdateDealerInfoTask().execute("");

			new UploadImageTask(mApp.getAllImgPaths().get(DEALER_KEY),
					companyImg).execute("");

		}
	};

	private String telNumber = "";// 手机号码
	private String companyName = "";// 公司名称
	private String companyPrincipal = "";// 负责人
	private String contactWay = "";// 联系方式
	private String companyAddress = "";// 公司地址
	private String companyOwnAddress = "";// 公司所有地
	private String companyPort = "";// 公司港口
	private String companyIntro = "";// 公司简介
	private String companyImg = "";// 公司形象照
	private String companyCity = "";

	class UpdateBaseInfoAdapter extends BaseAdapter {
		private Context context;
		private LayoutInflater mInflater;
		private TextWatcher textWatcher1 = new TextWatcher() {
			public void afterTextChanged(Editable paramEditable) {
			}

			public void beforeTextChanged(CharSequence paramCharSequence,
					int paramInt1, int paramInt2, int paramInt3) {
			}

			public void onTextChanged(CharSequence paramCharSequence,
					int paramInt1, int paramInt2, int paramInt3) {
				telNumber = paramCharSequence.toString();
			}
		};
		private TextWatcher textWatcher2 = new TextWatcher() {
			public void afterTextChanged(Editable paramEditable) {
			}

			public void beforeTextChanged(CharSequence paramCharSequence,
					int paramInt1, int paramInt2, int paramInt3) {
			}

			public void onTextChanged(CharSequence paramCharSequence,
					int paramInt1, int paramInt2, int paramInt3) {
				companyName = paramCharSequence.toString();
			}
		};
		private TextWatcher textWatcher3 = new TextWatcher() {
			public void afterTextChanged(Editable paramEditable) {
			}

			public void beforeTextChanged(CharSequence paramCharSequence,
					int paramInt1, int paramInt2, int paramInt3) {
			}

			public void onTextChanged(CharSequence paramCharSequence,
					int paramInt1, int paramInt2, int paramInt3) {
				companyPrincipal = paramCharSequence.toString();
			}
		};
		private TextWatcher textWatcher4 = new TextWatcher() {
			public void afterTextChanged(Editable paramEditable) {
			}

			public void beforeTextChanged(CharSequence paramCharSequence,
					int paramInt1, int paramInt2, int paramInt3) {
			}

			public void onTextChanged(CharSequence paramCharSequence,
					int paramInt1, int paramInt2, int paramInt3) {
				contactWay = paramCharSequence.toString();
			}
		};
		private TextWatcher textWatcher5 = new TextWatcher() {
			public void afterTextChanged(Editable paramEditable) {
			}

			public void beforeTextChanged(CharSequence paramCharSequence,
					int paramInt1, int paramInt2, int paramInt3) {
			}

			public void onTextChanged(CharSequence paramCharSequence,
					int paramInt1, int paramInt2, int paramInt3) {
				companyAddress = paramCharSequence.toString();
			}
		};
		private TextWatcher textWatcher6 = new TextWatcher() {
			public void afterTextChanged(Editable paramEditable) {
			}

			public void beforeTextChanged(CharSequence paramCharSequence,
					int paramInt1, int paramInt2, int paramInt3) {
			}

			public void onTextChanged(CharSequence paramCharSequence,
					int paramInt1, int paramInt2, int paramInt3) {
				companyCity = paramCharSequence.toString();
			}
		};

		private TextWatcher textWatcher7 = new TextWatcher() {
			public void afterTextChanged(Editable paramEditable) {
			}

			public void beforeTextChanged(CharSequence paramCharSequence,
					int paramInt1, int paramInt2, int paramInt3) {
			}

			public void onTextChanged(CharSequence paramCharSequence,
					int paramInt1, int paramInt2, int paramInt3) {
				companyPort = paramCharSequence.toString();
			}
		};

		private TextWatcher textWatcher8 = new TextWatcher() {
			public void afterTextChanged(Editable paramEditable) {
			}

			public void beforeTextChanged(CharSequence paramCharSequence,
					int paramInt1, int paramInt2, int paramInt3) {
			}

			public void onTextChanged(CharSequence paramCharSequence,
					int paramInt1, int paramInt2, int paramInt3) {
				companyIntro = paramCharSequence.toString();
			}
		};

		public UpdateBaseInfoAdapter(Context paramContext) {
			this.mInflater = LayoutInflater.from(paramContext);
			this.context = paramContext;
		}

		public int getCount() {
			return 8;
		}

		public Object getItem(int paramInt) {
			return "";
		}

		public long getItemId(int paramInt) {
			return paramInt;
		}

		public View getView(int paramInt, View paramView,
				ViewGroup paramViewGroup) {
			View localView = this.mInflater.inflate(R.layout.edit_dealer_input,
					null);
			EditText localEditText = (EditText) localView
					.findViewById(R.id.itemUserName);

			/*
			 * 参数一：telphone:注册手机号 参数二：compName:公司名称 参数三：compPeople:公司负责人
			 * 参数四：compTelphone:联系电话（要提示多个好嘛以，号分隔） 参数五：compAddress:公司地址
			 * 参数六：proviCity:公司所在地（省-市的方法 例如：四川-成都,系统绑定省市，用户自行选择）
			 * 参数七：compPort:公司所在港口(调用车源模块中查询港口的方法：GetCarAllPorts()查询绑定,供用户选择)
			 * 参数八：compIntro:公司简介
			 */
			if (paramInt == 0) {
				localView = mInflater.inflate(R.layout.my_base_items_avatar,
						null);

				TextView tx = (TextView) localView.findViewById(R.id.itemTitle);
				tx.setText("公司形象照");
				ImageView image = (ImageView) localView
						.findViewById(R.id.nextStep);
				ImageView imageContent = (ImageView) localView
						.findViewById(R.id.itemContent);
				imageContent.setImageBitmap(b);
				image.setVisibility(View.VISIBLE);
				// localEditText.setHint("注册手机号");
				// localEditText.setInputType(InputType.TYPE_CLASS_PHONE);
				// localEditText.addTextChangedListener(this.textWatcher1);
				localView
						.setBackgroundResource(android.R.drawable.list_selector_background);
				return localView;
			}

			if (paramInt == 1) {
				localEditText.setHint("公司名称");
				localEditText.setInputType(InputType.TYPE_CLASS_TEXT);
				localEditText.setText(d.getCompname());
				localEditText.addTextChangedListener(this.textWatcher2);
				return localView;
			}
			if (paramInt == 2) {
				localEditText.setHint("公司负责人");
				localEditText.setInputType(InputType.TYPE_CLASS_TEXT);
				localEditText.setText(d.getComppeople());
				localEditText.addTextChangedListener(this.textWatcher3);
				return localView;
			}
			if (paramInt == 3) {
				localEditText.setHint("联系方式，多个号码用逗号分隔");
				localEditText.setInputType(InputType.TYPE_CLASS_TEXT);
				localEditText.setText(d.getTelephone());
				localEditText.addTextChangedListener(this.textWatcher4);
				return localView;
			}
			if (paramInt == 4) {

				localEditText.setHint("公司地址");
				localEditText.setInputType(InputType.TYPE_CLASS_TEXT);
				localEditText.setText(d.getAddress());
				localEditText.addTextChangedListener(this.textWatcher5);
				return localView;
			}
			if (paramInt == 5) {
				// localView=mInflater.inflate(R.layout., paramViewGroup)
				// localEditText.setHint("公司所在城市：格式如：江苏-苏州");
				// localEditText.setInputType(InputType.TYPE_CLASS_TEXT);
				// localEditText.setText(d.getProvincecity());
				// localEditText.addTextChangedListener(this.textWatcher6);

				localView = mInflater.inflate(R.layout.base_list_items_simple,
						null);
				TextView textView = (TextView) localView
						.findViewById(R.id.itemContent);
				textView.setHintTextColor(context.getResources()
						.getColorStateList(R.color.font_gray_light_2));
				textView.setHint("公司所在省市：格式如：江苏-苏州");
				textView.setTextColor(context.getResources().getColorStateList(
						R.color.font_gray_light_2));
				String tmp = "";
				if (companyCity.equals("")) {
					tmp = d.getProvincecity();
				} else {
					tmp = companyCity;
				}
				textView.setText(tmp);

				// System.out.println("test=====");
				localView
						.setBackgroundResource(android.R.drawable.list_selector_background);
				return localView;
			}

			if (paramInt == 6) {

				localView = mInflater.inflate(R.layout.base_list_items_simple,
						null);
				TextView textView = (TextView) localView
						.findViewById(R.id.itemContent);
				textView.setHintTextColor(context.getResources()
						.getColorStateList(R.color.font_gray_light_2));

				textView.setHint("公司所在港口");
				textView.setTextColor(context.getResources().getColorStateList(
						R.color.font_gray_light_2));
				textView.setInputType(InputType.TYPE_CLASS_TEXT);

				String tmp = "";
				if (companyPort.equals("")) {
					tmp = d.getPort();
				} else {
					tmp = companyPort;
				}
				textView.setText(tmp);
				// localEditText.addTextChangedListener(this.textWatcher7);
				localView
						.setBackgroundResource(android.R.drawable.list_selector_background);
				return localView;
			}
			if (paramInt == 7) {

				localView = mInflater.inflate(
						R.layout.base_list_items_input_large, null);
				localEditText = (EditText) localView
						.findViewById(R.id.itemContent);
				localEditText.setHint("公司简介");
				localEditText.setInputType(InputType.TYPE_CLASS_TEXT);
				localEditText.setText(d.getIntro());
				localEditText.addTextChangedListener(this.textWatcher8);
				return localView;
			}
			return localView;
		}

		public boolean isEnabled(int position) {
			return super.isEnabled(position);
		}
	}

	private class UpdateDealerInfoTask extends
			AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {

			/**
			 * UpdateDealerIntro(string dealerId, string ports,string
			 * city,string compName,string compPeople,string telPhone,string
			 * compAddress, string intro,string userImg) 参数一：dealerId:当前用户ID
			 * 参数二：ports: 港口 参数三：city:城市 (格式如：江苏-苏州，中间以“-”号连接) 参数四：compName:公司名称
			 * 参数五：compPeople:公司负责人 参数六：telPhone:公司负责人电话 参数七：compAddress:公司地址
			 * 参数八：intro:公司简介 参数九：userImg:公司形象照
			 */

			HashMap<String, String> allParams = new HashMap<String, String>();
			UserInfo u = (UserInfo) readObject("userInfo");
			allParams.put("dealerId", u.getUserId());
			allParams.put("ports", companyPort);
			allParams.put("city", companyCity);
			allParams.put("compName", companyName);
			allParams.put("compPeople", companyPrincipal);
			allParams.put("telPhone", contactWay);
			allParams.put("compAddress", companyAddress);
			allParams.put("intro", companyIntro);
			allParams.put("userImg", companyImg);
			NetworkProgressUtils utils = NetworkProgressUtils.getInstance();
			publishProgress("");

			Object o = utils.getWebservicesByData(
					ConstantUtils.NAME_SPACE,
					ConstantUtils.ALL_METHROD_NAME.get(31),
					ConstantUtils.NAME_SPACE
							+ ConstantUtils.ALL_METHROD_NAME.get(31),
					ConstantUtils.GET_UPDATE_DEALER_INTRO_URL, allParams);

			if (o != null) {
				return o.toString();

			}
			return null;
		}

		@Override
		protected void onProgressUpdate(String... values) {
			showLoading("");
			super.onProgressUpdate(values);
		}

		@Override
		protected void onPostExecute(String result) {

			hideLoading();
			if (result != null) {

				if (result.indexOf("修改成功") >= 0) {

					showDialogFinish("修改成功", true);
				} else {
					// don't do anything...
				}
			}
			super.onPostExecute(result);
		}

	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View v, int position,
			long id) {

		if (position == 0) {
			cacheImage = (ImageView) v.findViewById(R.id.itemContent);
			// System.out.println("image===" + image);
			selectPhotoWay();

		} else if (position == 5) {

			Intent intent = new Intent();
			intent.setClass(this, PersonProvinceActivity.class);
			startActivity(intent);
			// System.out.println("onItemClick...");
		} else if (position == 6) {

			Intent intent = new Intent();
			intent.setClass(this, SelectorPortActivity.class);
			startActivity(intent);

		}

	}

	private ImageView cacheImage;

	private void selectPhotoWay() {
		String[] arrayOfString = "拍照,从相册中选择".split(",");
		AlertDialog.Builder localBuilder = new AlertDialog.Builder(this);
		localBuilder.setItems(arrayOfString,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface paramDialogInterface,
							int which) {
						photoDo(which);
					}
				});
		localBuilder.setNegativeButton("取消",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface paramDialogInterface,
							int paramInt) {
					}
				});
		localBuilder.create().show();
	}

	private void photoDo(int paramInt) {
		if (paramInt == 0) {
			if (Environment.getExternalStorageState().equals("mounted"))
				try {
					File localFile = new File(IMG_CACHE_PATH);
					if (!localFile.exists())
						localFile.mkdirs();
					Intent localIntent = new Intent(
							"android.media.action.IMAGE_CAPTURE");
					localIntent.putExtra("output",
							Uri.fromFile(new File(localFile, cameraFileName)));
					startActivityForResult(localIntent, 1);
					return;
				} catch (ActivityNotFoundException localActivityNotFoundException) {
					Toast.makeText(this, "没有找到储存目录", 1).show();
					return;
				}
			Toast.makeText(this, "请插入SD Card", Toast.LENGTH_SHORT).show();
			return;
		}
		startActivityForResult(new Intent("android.intent.action.PICK",
				MediaStore.Images.Media.EXTERNAL_CONTENT_URI), 2);
	}

	public static String IMG_CACHE_PATH = Environment
			.getExternalStorageDirectory().getAbsolutePath()
			+ "/ichehang/cache/pic/";
	private String cameraFileName = "car_add_tmp_pic";

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		Uri uri = null;
		if (requestCode == 1) {

			File localFile = new File(IMG_CACHE_PATH);
			uri = Uri.fromFile(new File(localFile, cameraFileName));

		} else if (requestCode == 2) {
			// System.out.println(data);
			if (data == null) {
				return;
			}
			uri = data.getData();

		}

		if (uri == null) {

			return;
		}

		String pathName = "";
		if (uri.toString().indexOf("content://") >= 0) {

			ContentResolver cr = getContentResolver();
			Cursor c = cr.query(uri, null, null, null, null);
			// System.out.println(c.getCount());
			c.moveToFirst();
			pathName = c.getString(c
					.getColumnIndex(MediaStore.Images.Media.DATA));

		} else {
			pathName = IMG_CACHE_PATH + cameraFileName;
			// System.out.println("pathName==" + pathName);
		}

		new CacheImageTask(cacheImage).execute(pathName);
	}

	/**
	 * 上传图片文件的任务
	 * 
	 * @author apple
	 * 
	 */
	class CacheImageTask extends AsyncTask<String, String, Boolean> {

		public CacheImageTask(ImageView img) {
			this.img = img;

		}

		private ImageView img;

		@Override
		protected Boolean doInBackground(String... params) {
			try {

				String pathName = params[0];
				String destPath = PublishCarPickPhotoActivity.COMPRESS_IMG_ROOT;
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmsS");
				String imgName = sdf.format(new Date());
				String destName = destPath + imgName;
				companyImg = imgName + ".png";
				boolean b = CompressImageUtils.writeImageToFile(pathName,
						destName);
				mApp.getAllImgPaths().put(DEALER_KEY, destName);
				return Boolean.valueOf(b);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return null;
		}

		@Override
		protected void onProgressUpdate(String... values) {

			showLoading("正在上传图片，请等待！");
			super.onProgressUpdate(values);
		}

		@Override
		protected void onPostExecute(Boolean result) {
			hideLoading();
			if (result != null && result.booleanValue()) {
				String str = mApp.getAllImgPaths().get(DEALER_KEY);
				Bitmap bitmap = ImageUtils.convertBitmapByPathName(str);

				img.setImageBitmap(bitmap);

			}

			super.onPostExecute(result);
		}

	}

	public static final String DEALER_KEY = "dealer_key";

	@Override
	protected void onResume() {

		super.onResume();

		this.companyCity = mApp.getmProvinceInfo();

		if (companyCity == null) {
			companyCity = "";
		}
		this.companyPort = mApp.getmPortInfo();

		if (this.companyPort == null) {
			this.companyPort = "";
		}
		UpdateBaseInfoAdapter adapter = new UpdateBaseInfoAdapter(this);
		list1.setAdapter(adapter);
	}

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
		mApp.setmPortInfo("");
		mApp.setmProvinceInfo("");
	}
}
